package com.sniff.atp.service.order;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.dto.ClientLoginDTO;
import com.sniff.atp.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.service.order
 * @Author: zxy
 * @CreateTime: 2022-11-09 22:28
 * @Description: Client: 创建混合商品订单
 * @Version: 1.0
 */
@Service
public class MixtureOrderService {
    @Autowired
    private CombinationOrderService combinationOrderService;
    @Autowired
    private CreateOrdinaryOrderService createOrdinaryOrderService;
    @Autowired
    private OEMOrderService oemOrderService;


    /**
     * client：添加购物车
     * @param clientLoginDTO
     * @param productData
     */
    public void addCart(ClientLoginDTO clientLoginDTO, JSONArray productData){

        for (int i = 0; i < productData.size(); i++) {
            JSONObject jsonObject = productData.getJSONObject(i);

            String productType = jsonObject.getString("productType");
            String productSku = jsonObject.getString("productSku");
            Integer quantity = Integer.parseInt(jsonObject.getString("quantity"));

            if (productType.equals("OEM")){
                for (int j = 0; j < quantity; j++) {
                    oemOrderService.oemAddCart(clientLoginDTO, productSku);
                }
            }
            if (productType.equals("normal")){
                createOrdinaryOrderService.addCart(productSku, quantity);
            }

            if (productType.equals("combination")){
                combinationOrderService.combinationAddCart(clientLoginDTO,productSku,quantity);
            }
        }
    }

    /**
     * client：创建订单流程
     */
    public String mixtureCreateOrderProcess(ClientLoginDTO clientLoginDTO,JSONArray productData, Integer orderType){
        createOrdinaryOrderService.setLogin(clientLoginDTO);
        createOrdinaryOrderService.deleteCart(clientLoginDTO);

        addCart(clientLoginDTO, productData);

        String s2 = createOrdinaryOrderService.cartList();
        ArrayList<String> cartIdList = new ArrayList<>();
        JSONObject cartDatas = JSON.parseObject(s2);
        JSONArray data = cartDatas.getJSONArray("data");
        for (Object cartData: data) {
            JSONArray cartList = ((JSONObject) cartData).getJSONArray("cartList");
            for (Object cartIds: cartList) {
                String cartId = ((JSONObject) cartIds).getString("cartId");
                cartIdList.add(cartId);
            }
        }
        LogUtil.warn("【订单流程】购物车列表查询！！");
        String order = createOrdinaryOrderService.createOrder(cartIdList, orderType);
        LogUtil.warn("【订单流程】创建订单成功，返回数据：" + order);
        return order;
    }

}
